package Servlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import db.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;

public class GetBlogsSevlet extends HttpServlet {
    public GetBlogsSevlet() {
        super();
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String author = "";
        String title = "";
        String id = request.getParameter("id");
        String text = "";
        String Code = "";
        String date = "";

        try {
            Connection connect = DBUtil.getConnect();
            Statement statement = connect.createStatement(); // Statement可以理解为数据库操作实例，对数据库的所有操作都通过它来实现
            ResultSet result;

            String sqlQuery = "select * from blogs where id ='" + id + "'";
            result = statement.executeQuery(sqlQuery);

            if(!result.next()){ // 不存在
                Code = "-2";
            } else { // 存在
                author = result.getString("author");
                title = result.getString("title");
                text = result.getString("text");
                date = result.getString("datetime");
                Code = "0";
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        HashMap<String, String> map = new HashMap<>();
        map.put("Code", Code);
        map.put("Title",title);
        map.put("Text",text);
        map.put("Author",author);
        map.put("Time",date);

        response.setContentType("text/html;charset=utf-8"); // 设置响应报文的编码格式
        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
        PrintWriter pw = response.getWriter(); // 获取 response 的输出流
        pw.print(gson.toJson(map)); // 通过输出流把业务逻辑的结果输出
        pw.flush();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
